import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {
	
	static String host = "localhost";
	static int port = 50000;
	static Scanner in = new Scanner(System.in);
	static Socket clientSocket;
	static PrintWriter out;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		boolean isConnected = false;
		while (!isConnected){
			promptSocketInfo();
			//printSocketInfo();
			
			
			// we instantiate the connection
			try {
				clientSocket = new Socket(host,port);
				isConnected =  true;
				System.out.println("Connection to server established");
			} catch (UnknownHostException e) {
				System.out.println("Unable to establish connection to server, please" +
						"make sure the host is valid and  the server is running.");
				continue;
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
			
			try {
				out = new PrintWriter(clientSocket.getOutputStream(), true);
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
			
			while(isConnected){
				String msg = promptMSG();
				out.println(msg);
				if(msg.equalsIgnoreCase("exit")){
					break;
				}
			}
			
			
		}
		if(out != null)
			out.close();
		if(clientSocket != null)
			clientSocket.close();
		
		System.out.println("Program exited properly");
	}
	private static String promptMSG(){
		System.out.println("Please enter the message you want to send (\"exit\" to close application): ");
		return in.nextLine();
	}
	
	private static void promptSocketInfo(){
		System.out.println("Please enter the ip address you want to connect to (press enter for localhost): ");
		String tempHost = in.nextLine();
		if (tempHost.length() != 0)
			host = tempHost;
		//System.out.println("Please enter the port:");
		//port = Integer.parseInt(in.nextLine());
	}
	
	private static void printSocketInfo(){
		System.out.println(host + ":" + port);
	}
}